package cn.iluwen.airline.Services;

import cn.iluwen.airline.DTOs.user.request.CreateOrderRequest;
import cn.iluwen.airline.DTOs.user.request.PassengerInfo;
import cn.iluwen.airline.DTOs.user.response.OrderResponse;
import cn.iluwen.airline.Entities.*;
import cn.iluwen.airline.Mapper.*;
import cn.iluwen.airline.utils.PageUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单服务类
 * 处理订单相关的业务逻辑
 */
@Service
public class OrderService {
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    
    @Autowired
    private FlightMapper flightMapper;
    
    @Autowired
    private AirportMapper airportMapper;
    
    @Autowired
    private SeatMapper seatMapper;
    
    /**
     * 创建订单
     * @param userId 用户ID
     * @param request 创建订单请求
     * @return 创建的订单
     */
    @Transactional
    public OrderResponse createOrder(String userId, CreateOrderRequest request) {
        // 查询航班信息
        Flight flight = flightMapper.findById(request.getFlightId());
        if (flight == null) {
            throw new RuntimeException("航班不存在");
        }
        
        if ("cancelled".equals(flight.getStatus())) {
            throw new RuntimeException("该航班已取消，无法预订");
        }
        
        // 检查座位可用性
        int economyRequestCount = 0;
        int businessRequestCount = 0;
        
        for (PassengerInfo passenger : request.getPassengers()) {
            if ("economy".equals(passenger.getTicketClass())) {
                economyRequestCount++;
            } else if ("business".equals(passenger.getTicketClass())) {
                businessRequestCount++;
            } else {
                throw new RuntimeException("无效的舱位类型: " + passenger.getTicketClass());
            }
        }
        
        // 获取可用座位数
        List<Seat> availableSeats = seatMapper.findAvailableSeatsByFlightId(flight.getFlightId());
        int availableEconomySeats = 0;
        int availableBusinessSeats = 0;
        
        for (Seat seat : availableSeats) {
            if ("economy".equals(seat.getSeatClass())) {
                availableEconomySeats++;
            } else if ("business".equals(seat.getSeatClass())) {
                availableBusinessSeats++;
            }
        }
        
        if (economyRequestCount > availableEconomySeats) {
            throw new RuntimeException("经济舱座位不足，当前可用: " + availableEconomySeats);
        }
        
        if (businessRequestCount > availableBusinessSeats) {
            throw new RuntimeException("商务舱座位不足，当前可用: " + availableBusinessSeats);
        }
        
        // 计算订单总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (PassengerInfo passenger : request.getPassengers()) {
            if ("economy".equals(passenger.getTicketClass())) {
                totalAmount = totalAmount.add(flight.getEconomyPrice());
            } else if ("business".equals(passenger.getTicketClass())) {
                totalAmount = totalAmount.add(flight.getBusinessPrice());
            }
        }
        
        // 创建订单
        Order order = new Order();
        order.setOrderId(UUID.randomUUID().toString());
        order.setUserId(userId);
        order.setOrderNumber(generateOrderNumber());
        order.setTotalAmount(totalAmount);
        order.setOrderStatus("pending"); // 默认状态为待付款
        order.setContactName(request.getContactName());
        order.setContactPhone(request.getContactPhone());
        order.setContactEmail(request.getContactEmail());
        order.setCreatedAt(LocalDateTime.now());
        
        orderMapper.insert(order);
        
        // 创建订单详情
        List<OrderDetail> orderDetails = new ArrayList<>();
        
        for (PassengerInfo passenger : request.getPassengers()) {
            OrderDetail detail = new OrderDetail();
            detail.setDetailId(UUID.randomUUID().toString());
            detail.setOrderId(order.getOrderId());
            detail.setFlightId(flight.getFlightId());
            detail.setPassengerName(passenger.getPassengerName());
            detail.setPassengerIdCard(passenger.getPassengerIdCard());
            detail.setSeatId(null); // 初始未选座
            
            if ("economy".equals(passenger.getTicketClass())) {
                detail.setTicketPrice(flight.getEconomyPrice());
            } else {
                detail.setTicketPrice(flight.getBusinessPrice());
            }
            
            detail.setTicketClass(passenger.getTicketClass());
            detail.setCheckInStatus(false); // 初始未值机
            
            orderDetails.add(detail);
        }
        
        orderDetailMapper.batchInsert(orderDetails);
        
        // 构建并返回响应
        return getOrderResponseById(order.getOrderId());
    }
    
    /**
     * 确认支付订单（模拟支付）
     * @param userId 用户ID
     * @param orderId 订单ID
     * @return 更新后的订单
     */
    @Transactional
    public OrderResponse payOrder(String userId, String orderId) {
        Order order = orderMapper.findById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        if (!order.getUserId().equals(userId)) {
            throw new RuntimeException("无权操作此订单");
        }
        
        if (!"pending".equals(order.getOrderStatus())) {
            throw new RuntimeException("订单状态不正确，当前状态: " + order.getOrderStatus());
        }
        
        // 模拟支付成功，更新订单状态为已支付
        orderMapper.updateStatus(orderId, "paid");
        
        return getOrderResponseById(orderId);
    }
    
    /**
     * 取消订单（只支持未支付订单）
     * @param userId 用户ID
     * @param orderId 订单ID
     * @return 更新后的订单
     */
    @Transactional
    public OrderResponse cancelOrder(String userId, String orderId) {
        Order order = orderMapper.findById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        if (!order.getUserId().equals(userId)) {
            throw new RuntimeException("无权操作此订单");
        }
        
        if ("cancelled".equals(order.getOrderStatus())) {
            throw new RuntimeException("订单已取消");
        }
        
        // 只允许取消未支付订单
        if (!"pending".equals(order.getOrderStatus())) {
            throw new RuntimeException("只有未支付订单可以取消，已支付订单请申请退票");
        }
        
        // 更新订单状态为已取消
        orderMapper.updateStatus(orderId, "cancelled");
        
        return getOrderResponseById(orderId);
    }
    
    /**
     * 退票操作（已支付订单）
     * @param userId 用户ID
     * @param orderId 订单ID
     * @return 更新后的订单
     */
    @Transactional
    public OrderResponse refundOrder(String userId, String orderId) {
        Order order = orderMapper.findById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        if (!order.getUserId().equals(userId)) {
            throw new RuntimeException("无权操作此订单");
        }
        
        if (!"paid".equals(order.getOrderStatus())) {
            throw new RuntimeException("只有已支付订单才能退票");
        }
        
        // 释放座位
        List<OrderDetail> details = orderDetailMapper.findByOrderId(orderId);
        for (OrderDetail detail : details) {
            if (detail.getSeatId() != null) {
                // 释放座位
                seatMapper.updateOccupiedStatus(detail.getSeatId(), false);
            }
        }
        
        // 直接退票（不需要管理员审核）
        orderMapper.updateStatus(orderId, "refunded");
        
        return getOrderResponseById(orderId);
    }
    
    /**
     * 获取用户的所有订单
     * @param userId 用户ID
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 订单列表
     */
    public PageInfo<OrderResponse> getUserOrders(String userId, Integer pageNum, Integer pageSize) {
        PageUtils.startPage(pageNum, pageSize);
        List<Order> orders = orderMapper.findByUserId(userId);
        PageInfo<Order> pageInfo = PageUtils.getPageInfo(orders);
        
        // 转换为响应DTO
        List<OrderResponse> responseList = orders.stream()
                .map(order -> getOrderResponseById(order.getOrderId()))
                .collect(Collectors.toList());
        
        // 构建分页响应
        PageInfo<OrderResponse> responsePage = new PageInfo<>();
        responsePage.setPageNum(pageInfo.getPageNum());
        responsePage.setPageSize(pageInfo.getPageSize());
        responsePage.setTotal(pageInfo.getTotal());
        responsePage.setPages(pageInfo.getPages());
        responsePage.setList(responseList);
        
        return responsePage;
    }
    
    /**
     * 获取订单详情
     * @param userId 用户ID
     * @param orderId 订单ID
     * @return 订单详情
     */
    public OrderResponse getOrderDetail(String userId, String orderId) {
        Order order = orderMapper.findById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        if (!order.getUserId().equals(userId)) {
            throw new RuntimeException("无权查看此订单");
        }
        
        return getOrderResponseById(orderId);
    }
    
    /**
     * 根据订单ID构建订单响应对象
     * @param orderId 订单ID
     * @return 订单响应
     */
    private OrderResponse getOrderResponseById(String orderId) {
        Order order = orderMapper.findById(orderId);
        if (order == null) {
            return null;
        }
        
        OrderResponse response = new OrderResponse();
        response.setOrderId(order.getOrderId());
        response.setOrderNumber(order.getOrderNumber());
        response.setTotalAmount(order.getTotalAmount());
        response.setOrderStatus(order.getOrderStatus());
        response.setContactName(order.getContactName());
        response.setContactPhone(order.getContactPhone());
        response.setContactEmail(order.getContactEmail());
        response.setCreatedAt(order.getCreatedAt());
        
        // 获取订单详情
        List<OrderDetail> details = orderDetailMapper.findByOrderId(orderId);
        if (!details.isEmpty()) {
            // 获取航班信息
            String flightId = details.get(0).getFlightId();
            Flight flight = flightMapper.findById(flightId);
            
            if (flight != null) {
                OrderResponse.FlightInfo flightInfo = new OrderResponse.FlightInfo();
                flightInfo.setFlightId(flight.getFlightId());
                flightInfo.setFlightNumber(flight.getFlightNumber());
                flightInfo.setDepartureTime(flight.getDepartureTime());
                flightInfo.setArrivalTime(flight.getArrivalTime());
                
                // 获取机场信息
                Airport departureAirport = airportMapper.findById(flight.getDepartureAirportId());
                if (departureAirport != null) {
                    flightInfo.setDepartureAirportCode(departureAirport.getAirportCode());
                    flightInfo.setDepartureAirportName(departureAirport.getAirportName());
                    flightInfo.setDepartureCity(departureAirport.getCity());
                }
                
                Airport arrivalAirport = airportMapper.findById(flight.getArrivalAirportId());
                if (arrivalAirport != null) {
                    flightInfo.setArrivalAirportCode(arrivalAirport.getAirportCode());
                    flightInfo.setArrivalAirportName(arrivalAirport.getAirportName());
                    flightInfo.setArrivalCity(arrivalAirport.getCity());
                }
                
                response.setFlight(flightInfo);
            }
            
            // 获取座位信息并构建机票信息
            List<OrderResponse.TicketInfo> tickets = new ArrayList<>();
            
            for (OrderDetail detail : details) {
                OrderResponse.TicketInfo ticket = new OrderResponse.TicketInfo();
                ticket.setDetailId(detail.getDetailId());
                ticket.setPassengerName(detail.getPassengerName());
                ticket.setPassengerIdCard(detail.getPassengerIdCard());
                ticket.setTicketPrice(detail.getTicketPrice());
                ticket.setTicketClass(detail.getTicketClass());
                ticket.setCheckInStatus(detail.getCheckInStatus());
                ticket.setSeatId(detail.getSeatId());
                
                // 获取座位号
                if (detail.getSeatId() != null) {
                    Seat seat = seatMapper.findById(detail.getSeatId());
                    if (seat != null) {
                        ticket.setSeatNumber(seat.getSeatNumber());
                    }
                }
                
                tickets.add(ticket);
            }
            
            response.setTickets(tickets);
        }
        
        return response;
    }
    
    /**
     * 生成订单编号
     * @return 订单编号
     */
    private String generateOrderNumber() {
        // 生成格式为：O+yyMMddHHmmss+4位随机数，总长度不超过20位
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHHmmss"));
        String randomNum = String.format("%04d", new Random().nextInt(10000));
        return "O" + timestamp + randomNum;
    }

    /**
     * 用户申请退票
     */
    @Transactional
    public void applyRefund(String userId, String orderId) {
        Order order = orderMapper.findById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            throw new RuntimeException("无权操作此订单");
        }
        if (!"paid".equals(order.getOrderStatus())) {
            throw new RuntimeException("只有已支付订单才能申请退票");
        }
        orderMapper.updateStatus(orderId, "refund_pending");
    }

    /**
     * 管理员同意退票
     */
    @Transactional
    public void adminApproveRefund(String orderId) {
        Order order = orderMapper.findById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!"refund_pending".equals(order.getOrderStatus())) {
            throw new RuntimeException("订单不在待退票审核状态");
        }
        // 释放座位
        List<OrderDetail> details = orderDetailMapper.findByOrderId(orderId);
        for (OrderDetail detail : details) {
            if (detail.getSeatId() != null) {
                seatMapper.updateOccupiedStatus(detail.getSeatId(), false);
            }
        }
        orderMapper.updateStatus(orderId, "refunded");
    }

    /**
     * 管理员拒绝退票
     */
    @Transactional
    public void adminRejectRefund(String orderId) {
        Order order = orderMapper.findById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!"refund_pending".equals(order.getOrderStatus())) {
            throw new RuntimeException("订单不在待退票审核状态");
        }
        orderMapper.updateStatus(orderId, "refund_rejected");
    }

    /**
     * 查询所有待审核退票订单
     */
    public List<Order> getRefundPendingOrders() {
        return orderMapper.findByStatus("refund_pending");
    }

    /**
     * 管理员分页查询所有订单（可选按状态、关键词筛选）
     */
    public PageInfo<OrderResponse> getAllOrders(Integer pageNum, Integer pageSize, String status, String keyword) {
        PageUtils.startPage(pageNum, pageSize);
        List<Order> orders;
        if (status != null && !status.isEmpty()) {
            orders = orderMapper.findByStatus(status);
        } else {
            orders = orderMapper.findOrdersWithPaging();
        }
        // 关键词筛选（如有）
        if (keyword != null && !keyword.isEmpty()) {
            orders = orders.stream().filter(order ->
                (order.getOrderNumber() != null && order.getOrderNumber().contains(keyword)) ||
                (order.getContactName() != null && order.getContactName().contains(keyword)) ||
                (order.getContactPhone() != null && order.getContactPhone().contains(keyword))
            ).collect(Collectors.toList());
        }
        PageInfo<Order> pageInfo = PageUtils.getPageInfo(orders);
        List<OrderResponse> responseList = orders.stream()
                .map(order -> getOrderResponseById(order.getOrderId()))
                .collect(Collectors.toList());
        PageInfo<OrderResponse> responsePage = new PageInfo<>();
        responsePage.setPageNum(pageInfo.getPageNum());
        responsePage.setPageSize(pageInfo.getPageSize());
        responsePage.setTotal(pageInfo.getTotal());
        responsePage.setPages(pageInfo.getPages());
        responsePage.setList(responseList);
        return responsePage;
    }

    /**
     * 管理员获取订单详情（不校验userId）
     */
    public OrderResponse getOrderDetailByAdmin(String orderId) {
        return getOrderResponseById(orderId);
    }

    /**
     * 管理员删除订单（连带删除订单详情）
     */
    @Transactional
    public boolean deleteOrderByAdmin(String orderId) {
        orderDetailMapper.deleteByOrderId(orderId);
        int rows = orderMapper.delete(orderId);
        return rows > 0;
    }

    /**
     * 管理员修改订单状态
     */
    @Transactional
    public boolean updateOrderStatusByAdmin(String orderId, String status) {
        int rows = orderMapper.updateStatus(orderId, status);
        return rows > 0;
    }

    /**
     * 管理员取消订单（释放座位，状态设为cancelled）
     */
    @Transactional
    public boolean cancelOrderByAdmin(String orderId) {
        Order order = orderMapper.findById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if ("cancelled".equals(order.getOrderStatus())) {
            return false;
        }
        // 如果订单已支付，需要释放座位
        if ("paid".equals(order.getOrderStatus())) {
            List<OrderDetail> details = orderDetailMapper.findByOrderId(orderId);
            for (OrderDetail detail : details) {
                if (detail.getSeatId() != null) {
                    seatMapper.updateOccupiedStatus(detail.getSeatId(), false);
                }
            }
        }
        orderMapper.updateStatus(orderId, "cancelled");
        return true;
    }

    /**
     * 获取用户所有已支付且未全部值机的订单
     */
    public List<Order> getPaidUnCheckedInOrders(String userId) {
        List<Order> orders = orderMapper.findByUserId(userId);
        List<Order> result = new ArrayList<>();
        for (Order order : orders) {
            if (!"paid".equals(order.getOrderStatus())) continue;
            List<OrderDetail> details = orderDetailMapper.findByOrderId(order.getOrderId());
            if (details.stream().anyMatch(d -> !Boolean.TRUE.equals(d.getCheckInStatus()))) {
                result.add(order);
            }
        }
        return result;
    }

    /**
     * 获取订单详情列表
     */
    public List<OrderDetail> getOrderDetails(String orderId) {
        return orderDetailMapper.findByOrderId(orderId);
    }

    /**
     * 验证改签航线
     * 确保新航班与原订单的航线（出发地/目的地）相同
     * @param userId 用户ID
     * @param orderId 订单ID
     * @param newFlightId 新航班ID
     */
    public void validateRescheduleRoute(String userId, String orderId, String newFlightId) {
        // 验证订单
        Order order = orderMapper.findById(orderId);
        if (order == null) throw new RuntimeException("订单不存在");
        if (!order.getUserId().equals(userId)) throw new RuntimeException("无权操作此订单");
        if (!"paid".equals(order.getOrderStatus())) throw new RuntimeException("只有已支付订单才能改签");
        
        // 获取原订单航班信息
        List<OrderDetail> details = orderDetailMapper.findByOrderId(orderId);
        if (details.isEmpty()) throw new RuntimeException("订单详情不存在");
        
        String originalFlightId = details.get(0).getFlightId();
        Flight originalFlight = flightMapper.findById(originalFlightId);
        if (originalFlight == null) throw new RuntimeException("原航班不存在");
        
        // 获取新航班信息
        Flight newFlight = flightMapper.findById(newFlightId);
        if (newFlight == null) throw new RuntimeException("新航班不存在");
        
        // 验证航线相同
        if (!originalFlight.getDepartureAirportId().equals(newFlight.getDepartureAirportId()) || 
            !originalFlight.getArrivalAirportId().equals(newFlight.getArrivalAirportId())) {
            throw new RuntimeException("改签航班必须与原航班保持相同的出发地和目的地");
        }
    }
    
    /**
     * 用户发起改签申请
     * @param userId 用户ID
     * @param orderId 订单ID
     * @param newFlightId 新航班ID
     */
    @Transactional
    public void rescheduleOrder(String userId, String orderId, String newFlightId) {
        Order order = orderMapper.findById(orderId);
        if (order == null) throw new RuntimeException("订单不存在");
        if (!order.getUserId().equals(userId)) throw new RuntimeException("无权操作此订单");
        if (!"paid".equals(order.getOrderStatus())) throw new RuntimeException("只有已支付订单才能改签");
        
        // 获取原订单航班信息
        List<OrderDetail> details = orderDetailMapper.findByOrderId(orderId);
        if (details.isEmpty()) throw new RuntimeException("订单详情不存在");
        
        String originalFlightId = details.get(0).getFlightId();
        Flight originalFlight = flightMapper.findById(originalFlightId);
        if (originalFlight == null) throw new RuntimeException("原航班不存在");
        
        // 获取新航班信息
        Flight newFlight = flightMapper.findById(newFlightId);
        if (newFlight == null) throw new RuntimeException("新航班不存在");
        
        // 验证航线相同
        if (!originalFlight.getDepartureAirportId().equals(newFlight.getDepartureAirportId()) || 
            !originalFlight.getArrivalAirportId().equals(newFlight.getArrivalAirportId())) {
            throw new RuntimeException("改签航班必须与原航班保持相同的出发地和目的地");
        }
        
        // 保存原邮箱和改签信息
        String originalEmail = order.getContactEmail();
        String combinedInfo = "email:" + (originalEmail == null ? "" : originalEmail) + 
                             ",newFlightId:" + newFlightId;
        
        // 更新订单状态和信息
        order.setOrderStatus("reschedule_pending");
        order.setContactEmail(combinedInfo);
        orderMapper.update(order);
    }
    
    /**
     * 管理员同意改签
     * @param orderId 原订单ID
     */
    @Transactional
    public void adminApproveReschedule(String orderId) {
        Order order = orderMapper.findById(orderId);
        if (order == null) throw new RuntimeException("订单不存在");
        if (!"reschedule_pending".equals(order.getOrderStatus())) throw new RuntimeException("订单不在待改签审核状态");
        
        // 解析信息：提取原邮箱和新航班ID
        String info = order.getContactEmail();
        if (info == null) throw new RuntimeException("缺少改签信息");
        
        String originalEmail = "";
        String newFlightId = null;
        
        // 处理复合格式：email:xxx,newFlightId:xxx
        if (info.contains("email:") && info.contains("newFlightId:")) {
            int emailStartIndex = info.indexOf("email:") + "email:".length();
            int newFlightIdIndex = info.indexOf(",newFlightId:");
            
            if (newFlightIdIndex > emailStartIndex) {
                originalEmail = info.substring(emailStartIndex, newFlightIdIndex);
                newFlightId = info.substring(newFlightIdIndex + ",newFlightId:".length());
            }
        } 
        // 兼容旧格式：只有newFlightId:xxx
        else if (info.contains("newFlightId:")) {
            newFlightId = info.substring(info.indexOf("newFlightId:") + "newFlightId:".length());
        }
        
        if (newFlightId == null || newFlightId.isEmpty()) {
            throw new RuntimeException("改签信息不完整");
        }
        
        // 获取原订单详情
        List<OrderDetail> details = orderDetailMapper.findByOrderId(orderId);
        if (details.isEmpty()) throw new RuntimeException("订单详情不存在");
        OrderDetail originalDetail = details.get(0);
        
        // 获取原座位编号
        String originalSeatNumber = null;
        if (originalDetail.getSeatId() != null) {
            Seat originalSeat = seatMapper.findById(originalDetail.getSeatId());
            if (originalSeat != null) {
                originalSeatNumber = originalSeat.getSeatNumber();
            }
        }
        
        Seat newSeat = null;
        
        // 如果原订单有座位，尝试在新航班上查找相同位置的座位
        if (originalSeatNumber != null) {
            newSeat = seatMapper.findByFlightIdAndSeatNumber(newFlightId, originalSeatNumber);
            // 如果找到了相同位置的座位但已被占用，则设为null以便随机分配
            if (newSeat != null && Boolean.TRUE.equals(newSeat.getIsOccupied())) {
                newSeat = null;
            }
        }
        
        // 如果没有原座位或原座位在新航班上不可用，则随机分配一个座位
        if (newSeat == null) {
            List<Seat> availableSeats = seatMapper.findAvailableSeatsByFlightId(newFlightId);
            if (availableSeats == null || availableSeats.isEmpty()) {
                throw new RuntimeException("新航班上没有可用座位");
            }
            
            // 尝试匹配相同舱位等级的座位
            String ticketClass = originalDetail.getTicketClass();
            List<Seat> matchingSeats = availableSeats.stream()
                .filter(seat -> ticketClass.equals(seat.getSeatClass()))
                .collect(Collectors.toList());
            
            if (!matchingSeats.isEmpty()) {
                // 有匹配舱位等级的座位，随机选一个
                int randomIndex = new Random().nextInt(matchingSeats.size());
                newSeat = matchingSeats.get(randomIndex);
            } else if (!availableSeats.isEmpty()) {
                // 没有匹配舱位等级的座位，只要有任何可用座位就行
                int randomIndex = new Random().nextInt(availableSeats.size());
                newSeat = availableSeats.get(randomIndex);
            } else {
                throw new RuntimeException("新航班上没有可用座位");
            }
        }
        
        // 如果原座位存在，则释放它
        if (originalDetail.getSeatId() != null) {
            seatMapper.updateOccupiedStatus(originalDetail.getSeatId(), false);
        }
        
        // 原订单状态设为reschedule_approved
        order.setOrderStatus("reschedule_approved");
        order.setContactEmail(originalEmail); // 恢复原始邮箱
        orderMapper.update(order);
        
        // 创建新订单（新航班/相同座位，状态为paid）
        Order newOrder = new Order();
        newOrder.setOrderId(UUID.randomUUID().toString());
        newOrder.setUserId(order.getUserId());
        newOrder.setOrderNumber(generateOrderNumber());
        
        // 获取新航班价格
        Flight newFlight = flightMapper.findById(newFlightId);
        String ticketClass = originalDetail.getTicketClass(); // 保持与原订单相同的舱位等级
        BigDecimal ticketPrice;
        if ("business".equals(ticketClass)) {
            ticketPrice = newFlight.getBusinessPrice();
        } else {
            ticketPrice = newFlight.getEconomyPrice();
        }
        
        newOrder.setTotalAmount(ticketPrice);
        newOrder.setOrderStatus("paid");
        newOrder.setContactName(order.getContactName());
        newOrder.setContactPhone(order.getContactPhone());
        newOrder.setContactEmail(originalEmail); // 使用解析出的原始邮箱
        newOrder.setCreatedAt(LocalDateTime.now());
        orderMapper.insert(newOrder);
        
        // 新订单详情
        OrderDetail newDetail = new OrderDetail();
        newDetail.setDetailId(UUID.randomUUID().toString());
        newDetail.setOrderId(newOrder.getOrderId());
        newDetail.setFlightId(newFlightId);
        newDetail.setPassengerName(originalDetail.getPassengerName());
        newDetail.setPassengerIdCard(originalDetail.getPassengerIdCard());
        newDetail.setSeatId(newSeat.getSeatId());
        newDetail.setTicketPrice(ticketPrice);
        newDetail.setTicketClass(ticketClass);
        newDetail.setCheckInStatus(false);
        orderDetailMapper.insert(newDetail);
        
        // 占用新座位
        seatMapper.updateOccupiedStatus(newSeat.getSeatId(), true);
    }

    /**
     * 管理员拒绝改签
     * @param orderId 原订单ID
     */
    @Transactional
    public void adminRejectReschedule(String orderId) {
        Order order = orderMapper.findById(orderId);
        if (order == null) throw new RuntimeException("订单不存在");
        if (!"reschedule_pending".equals(order.getOrderStatus())) throw new RuntimeException("订单不在待改签审核状态");
        // 恢复订单状态为paid，清空临时信息
        order.setOrderStatus("paid");
        order.setContactEmail(null);
        orderMapper.update(order);
    }

    /**
     * 查询所有待审核改签订单
     */
    public List<Order> getReschedulePendingOrders() {
        return orderMapper.findByStatus("reschedule_pending");
    }
} 